let root = [2, 1, 3, 4, 5];
function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
}
function arrayToTree(arr) {
    if (arr.length === 0 || arr[0] === null) return null;
    const root = new TreeNode(arr[0]);
    const queue = [root];
    let i = 1;
    while (queue.length > 0 && i < arr.length) {
        const current = queue.shift();

        // 处理左子节点
        if (i < arr.length && arr[i] !== null) {
            current.left = new TreeNode(arr[i]);
            queue.push(current.left);
        }
        i++;

        // 处理右子节点
        if (i < arr.length && arr[i] !== null) {
            current.right = new TreeNode(arr[i]);
            queue.push(current.right);
        }
        i++;
    }

    return root;
}
var invertTree = function (root) {
    if (!root) {
        return null;
    }
    const queue = [root];
    while (queue.length > 0) {
        const cur = queue.shift();
        // 交换左右子节点
        const temp = cur.left;
        cur.left = cur.right;
        cur.right = temp;

        // 若左子节点不为空，将其加入队列
        if (cur.left) {
            queue.push(cur.left);
        }
        // 若右子节点不为空，将其加入队列
        if (cur.right) {
            queue.push(cur.right);
        }
    }
    return root;
};
console.log(invertTree(arrayToTree(root)));